package com.xuelang.pipeline.entry.resource;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.beust.jcommander.internal.Lists;
import com.xuelang.pipeline.app.resource.ClusterService;
import com.xuelang.pipeline.app.resource.EnvironmentService;
import com.xuelang.pipeline.app.resource.SpaceService;
import com.xuelang.pipeline.app.resource.util.TektonUtil;
import com.xuelang.pipeline.client.common.constant.Constant;
import com.xuelang.pipeline.client.common.result.ApiResult;
import com.xuelang.pipeline.client.common.util.BizAssert;
import com.xuelang.pipeline.client.resource.IPodService;
import com.xuelang.pipeline.client.resource.dto.*;
import com.xuelang.pipeline.worker.client.pod.dto.PodQueryDTO;
import com.xuelang.pipeline.worker.client.pod.dto.QueryDTO;
import io.kubernetes.client.openapi.models.V1ContainerStatus;
import io.kubernetes.client.openapi.models.V1PodList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Pod服务web控制类
 *
 * @author xiwen.zxg
 * @since 2024/5/28
 */
@Slf4j
@RestController
@RequestMapping("/pod")
public class PodController implements IPodService {

    @Autowired
    com.xuelang.pipeline.worker.client.pod.IPodService podService;
    @Autowired
    EnvironmentService environmentService;
    @Autowired
    SpaceService spaceService;
    @Autowired
    ClusterService clusterService;


    @Override
    public ApiResult<List<PodListDTO>> list(@RequestBody @Valid PodListVO podListVO) {
        EnvironmentDTO environmentDTO = environmentService.query(podListVO.getEnvironmentUuid());
        BizAssert.notNull(environmentDTO, "环境不存在");
        BizAssert.notEmpty(environmentDTO.getSpaceUuid(), "请配置环境所属交付空间.");
        SpaceDTO spaceDTO = spaceService.query(environmentDTO.getSpaceUuid());
        BizAssert.notNull(spaceDTO, "交付空间不存在");
        BizAssert.notEmpty(environmentDTO.getSpaceUuid(), "请配置交付空间所属集群.");
        ClusterDTO clusterDTO = clusterService.query(spaceDTO.getClusterUuid());
        BizAssert.notNull(clusterDTO, "集群不存在");
        BizAssert.notEmpty(clusterDTO.getKubeConfig(), "请配置集群凭证.");

        String componentLabel = podListVO.getComponentLabel();

//        PodListRequest podListRequest = new PodListRequest();
//        podListRequest.setKubeConfig(clusterDTO.getKubeConfig());
//        podListRequest.setNamespaceName(spaceDTO.getNamespace());
//        if (StringUtils.isNotBlank(componentLabel)) {
//            podListRequest.setLabelName(getLabelKey(componentLabel));
//        }
//        podListRequest.setPodName(podListVO.getPodName());

        QueryDTO podListRequest = new QueryDTO();
        podListRequest.setKubeConfig(clusterDTO.getKubeConfig());
        podListRequest.setNamespaceName(spaceDTO.getNamespace());
        if (StringUtils.isNotBlank(componentLabel)) {
            podListRequest.setLabelName(getLabelKey(componentLabel));
        }
        podListRequest.setPodName(podListVO.getPodName());

        com.xuelang.pipeline.worker.client.common.result.ApiResult<V1PodList> podList = podService.getPodList(podListRequest);
        V1PodList data = podList.getData();
        // 判空
        if (Objects.isNull(data) || CollectionUtils.isEmpty(data.getItems())) {
            return ApiResult.success(Lists.newArrayList());
        }
        List<PodListDTO> podDTOList = new ArrayList<>();
        data.getItems().forEach(v1Pod -> {
            PodListDTO podDTO = new PodListDTO();
            podDTO.setNamespaceName(spaceDTO.getNamespace());
            podDTO.setPodName(Objects.requireNonNull(v1Pod.getMetadata()).getName());
            podDTO.setCreateTime(TektonUtil.offsetDateTime2Str(Objects.requireNonNull(v1Pod.getStatus()).getStartTime()));
            podDTO.setReady(TektonUtil.getPodReadyStatus(v1Pod.getStatus().getConditions()));
            podDTO.setIp(v1Pod.getStatus().getPodIP() != null ? v1Pod.getStatus().getPodIP() : null);
            podDTO.setNodeName(v1Pod.getSpec().getNodeName());
            List<V1ContainerStatus> containerStatuses = v1Pod.getStatus().getContainerStatuses();
            if(CollectionUtils.isNotEmpty(containerStatuses)) {
                podDTO.setDockerDTOList(containerStatuses.stream().map(c ->
                        new DockerDTO(c.getContainerID(), c.getName(), c.getImage())).collect(Collectors.toList()));
            }
            podDTO.setStatus(v1Pod.getStatus().getPhase());
            podDTOList.add(podDTO);
        });
        return ApiResult.success(podDTOList);
    }

    @Override
    public ApiResult<String> log(@RequestBody @Valid PodLogVO podLogVO) {
        EnvironmentDTO environmentDTO = environmentService.query(podLogVO.getEnvironmentUuid());
        BizAssert.notNull(environmentDTO, "环境不存在");
        BizAssert.notEmpty(environmentDTO.getSpaceUuid(), "请配置环境所属交付空间.");
        SpaceDTO spaceDTO = spaceService.query(environmentDTO.getSpaceUuid());
        BizAssert.notNull(spaceDTO, "交付空间不存在");
        BizAssert.notEmpty(environmentDTO.getSpaceUuid(), "请配置交付空间所属集群.");
        ClusterDTO clusterDTO = clusterService.query(spaceDTO.getClusterUuid());
        BizAssert.notNull(clusterDTO, "集群不存在");
        BizAssert.notEmpty(clusterDTO.getKubeConfig(), "请配置集群凭证.");

//        PodLogRequest podLogRequest = new PodLogRequest();
//        podLogRequest.setKubeConfig(clusterDTO.getKubeConfig());
//        podLogRequest.setNamespaceName(spaceDTO.getNamespace());
//        podLogRequest.setLabelName(getLabelKey(podLogVO.getComponentLabel()));
//        podLogRequest.setPodName(podLogVO.getPodName());
//        podLogRequest.setContainer(podLogVO.getContainer());
//        podLogRequest.setLimit(podLogVO.getLimit());

        PodQueryDTO podLogRequest = new PodQueryDTO();
        podLogRequest.setKubeConfig(clusterDTO.getKubeConfig());
        podLogRequest.setNamespaceName(spaceDTO.getNamespace());
//        podLogRequest.setLabelName(getLabelKey(podLogVO.getComponentLabel()));
        podLogRequest.setPodName(podLogVO.getPodName());
        podLogRequest.setContainer(podLogVO.getContainer());
        podLogRequest.setLimit(podLogVO.getLimit());

        com.xuelang.pipeline.worker.client.common.result.ApiResult<String> podLog = podService.getPodLog(podLogRequest);

        return ApiResult.success(podLog.getData());
    }

    /**
     * 获取标签key
     *
     * @param componentCode
     * @return
     */
    private String getLabelKey(String componentCode) {
        return Constant.COMPONENT_LABEL_KEY_PREFIX + componentCode;
    }

}
